﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;

namespace WeiXinMongoApis.Controllers
{
    public class LoginLogController : ApiController
    {
        public string Get(string clientId)
        {

            string logFileName = string.Concat("Log/Login", DateTime.Now.ToString("yyyyMMdd"), ".txt");
            using (FileStream file = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, logFileName), FileMode.Append))
            {
                StreamWriter sw = new StreamWriter(file);
                StringBuilder sb = new StringBuilder();
                string[] splitedArgs = clientId.Split(',');
                //操作系统版本
                var osVersion = "";
                //应用程序当前目录
                var currentDirectory = "";
                //机器名
                var machineName = "";
                //当前登录用户
                var userName = "";
                //Mac地址
                var macAddress = "";
                //硬盘ID
                var hardID = "";
                //主板ID
                var motherboard = "";
                if (splitedArgs.Length >= 5)
                {
                    osVersion = splitedArgs[1];
                    currentDirectory = splitedArgs[2];
                    machineName = splitedArgs[3];
                    userName = splitedArgs[4];
                    macAddress = splitedArgs[5];
                    hardID = splitedArgs[6];
                    motherboard = splitedArgs[7];
                }

                string[] data = { splitedArgs[0], DateTime.Now.ToString(), this.GetClientIp(), osVersion, currentDirectory, machineName, userName, macAddress, hardID, motherboard };
                sw.WriteLine(string.Join(",", data.ToArray()), true);
                sw.Close();
            }
            return "";
        }

        private const string HttpContext = "MS_HttpContext";

        private string GetClientIp()
        {
            try
            {
                if (this.Request.Properties.ContainsKey(HttpContext))
                {
                    HttpContextWrapper ctx = (HttpContextWrapper)this.Request.Properties[HttpContext];
                    if (ctx != null)
                    {
                        return ctx.Request.UserHostAddress;
                    }
                }
            }
            catch (Exception)
            {
                return "unknown";
            }
            return "unknown";
        }

    }
}
